package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;


//@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决中文乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

//       //获得浏览器请求数据
//        Map<String, String[]> map = request.getParameterMap();
//
//        //创建user对象
//        User user = new User();
//
//        //将数据封装到map集合中
//        try {
//            BeanUtils.populate(user,map);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //利用业务对象调用方法,判断用户在数据库是否存在
        boolean result = new UserService().checkUser(new User(null,username,password));

        //判断结果
        if(result){
            //如果为true,则说明登陆成功,跳转成功页面
            response.sendRedirect("/success.html");
        }else{
            //false跳转失败页面
            response.getWriter().println("<h1>登陆失败,用户名或密码错误!请重新登录!</h1>");
            response.setHeader("refresh","2;url=http://localhost:8080/login.html");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}